﻿using System;
using Microsoft.Win32;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;
using System.IO;
using System.Net;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using NotesFor.HtmlToOpenXml;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace LoadTestReport
{
    public partial class UserControl1 : UserControl
    {
        private BackgroundWorker reportWorker;
        private ProgressWindow _ProgressWindow;

        public UserControl1()
        {
            InitializeComponent();
            readUserPref();
            RegistryKey pRegKey = Registry.CurrentUser;
            try
            {
                pRegKey = pRegKey.OpenSubKey("Software\\Microsoft\\VisualStudio\\10.0\\EnterpriseTools\\QualityTools\\Controller");
                if (pRegKey == null)
                {
                    pRegKey = Registry.CurrentUser;
                    pRegKey = pRegKey.OpenSubKey("Software\\Microsoft\\VisualStudio\\11.0\\EnterpriseTools\\QualityTools\\Controller");
                }

                if (pRegKey != null)
                {
                    String connString = (String)pRegKey.GetValue("LoadTestResultsDisplayConnectString");
                    textBoxConnString.Text = connString;
                    Console.WriteLine("LoadTestResultsDisplayConnectString=" + connString);
                }
            }
            catch (Exception ex) 
            {
                EventLog m_EventLog = new EventLog("");
                m_EventLog.Source = "MagicReports";
                m_EventLog.WriteEntry( ex.Message, EventLogEntryType.Error);
            }

            if (textBoxConnString.Text == null || textBoxConnString.Text == "")
            {
                textBoxConnString.Text = "Data Source=\"MachineName\\SQLEXPRESS\";Initial Catalog=LoadTest2010;Integrated Security=True";
            }            

            for (int i = 0; i < checkedListReportOptions1.Items.Count; i++) checkedListReportOptions1.SetItemChecked(i, true);
            for (int i = 0; i < checkedListReportOptions2.Items.Count - 1; i++) checkedListReportOptions2.SetItemChecked(i, true);
            panel2.Enabled = false;

            checkedListReportOptions2.ItemCheck += UserControl1_Checked;
        }

        void UserControl1_Checked(object sender, EventArgs e)
        {
            ItemCheckEventArgs ee = (ItemCheckEventArgs)e;
            CheckedListBox box = (CheckedListBox)sender;
            String itemText = box.SelectedItem.ToString();
            TestParent.iSAllcounterChecked = true;
            if (itemText.Contains("All other counters available for the test") && (ee.NewValue.ToString()=="Checked"))
            {
                Thread _plz_th = new Thread(startPlzWait);
                _plz_th.SetApartmentState(ApartmentState.STA);
                _plz_th.Start();
                
                Thread _Thread = new Thread(ShowCounterWindow);
                _Thread.SetApartmentState(ApartmentState.STA);
                _Thread.Start();                
            }
            else if ((ee.NewValue.ToString() == "Unchecked"))
            {
                TestParent.iSAllcounterChecked = false;
            }
            this.listViewTestRuns.Focus();
        }

        private void startPlzWait(object o)
        {
            PleaseWait plz = new PleaseWait();
            plz.Show();
            Thread.Sleep(1000);
            plz.Close();
        }

        private void ShowCounterWindow(object obj)
        {
            SelectCounters _SelectCounters = new SelectCounters();
            _SelectCounters.ShowDialog();
        }

        private void readUserPref()
        {
            String[] userPrefs = File.ReadAllLines("C:\\Templates\\userPref.txt");
            for (int i = 0; i < userPrefs.Length; i++)
            {
                String[] keyVals = userPrefs[i].Split('$');
                
                if (keyVals[0] == "") continue;

                if (keyVals[0] == "strtextBoxReportName")
                {
                    textBoxReportName.Text = keyVals[1];
                }
                else if (keyVals[0] == "strtextAreaEnv")
                {
                    textAreaEnv.Text = keyVals[1] + Environment.NewLine;
                }
                else if (keyVals[0] == "strtextBoxDeploymentDiag")
                {
                    textBoxDeploymentDiag.Text = keyVals[1];
                }
                else
                {
                    textAreaEnv.Text += keyVals[0] + Environment.NewLine;
                }
            }
        }

        private void ConnectButtonClicked(object sender, EventArgs e)
        {
            panel2.Enabled = false;
            listViewTestRuns.Items.Clear();
            String connString = textBoxConnString.Text;
            if ("" == connString || connString == null)
            {
                MessageBox.Show("Invalid Connection String");
                return;
            }
            TestParent.connString = connString;

            ArrayList testList = DAO.DataReader.getAllTestRuns();

            if (testList == null) 
            { 
                MessageBox.Show("Database Cannot be connected"); 
                this.buttonProceedOptions.Enabled = false;
                return;
            }
            this.buttonProceedOptions.Enabled = true;
            listViewTestRuns.View = System.Windows.Forms.View.Details;
            listViewTestRuns.GridLines = true;
            listViewTestRuns.FullRowSelect = true;
            listViewTestRuns.MultiSelect = false;



            listViewTestRuns.Columns.Add("Run ID", 60, HorizontalAlignment.Left);
            listViewTestRuns.Columns.Add("Test Name", 100, HorizontalAlignment.Left);
            listViewTestRuns.Columns.Add("Start Time", 130, HorizontalAlignment.Left);
            listViewTestRuns.Columns.Add("End Time", 130, HorizontalAlignment.Left);
            listViewTestRuns.Columns.Add("Duration", 80, HorizontalAlignment.Right);
            listViewTestRuns.Columns.Add("Outcome", 70, HorizontalAlignment.Left);
            listViewTestRuns.Columns.Add("Conc. Users", 80, HorizontalAlignment.Right);

            for (int i = 0; i < testList.Count; i++)
            {
                String[] row = new String[7];

                Dictionary<String, String> dict = (Dictionary<String, String>)testList[i];
                row[0] = dict["runID"];
                row[1] = dict["testName"];
                row[2] = dict["startTime"];
                row[3] = dict["endTime"];
                row[4] = Int16.Parse(dict["runDuration"].ToString())/60 + " (m)";
                row[5] = dict["outcome"];
                row[6] = dict["users"];

                listViewTestRuns.Items.Add(new ListViewItem(row));
            }
        }

        private void buttonProceedOptionsClicked(object sender, EventArgs e)
        {
            if (listViewTestRuns.SelectedItems.Count == 0)
            {
                MessageBox.Show("Please select a Test Run");
                return;
            }
            clearTestParent();

            String runID = listViewTestRuns.SelectedItems[0].SubItems[0].Text;
            TestParent.selectedRunID = int.Parse(runID);
            this.listViewTestRuns.Focus();
            listViewTestRuns.SelectedItems[0].Selected = true;
            panel2.Enabled = true;            
        }

        private void clearTestParent()
        {
        TestParent.ProgressPercentage = 0;
        TestParent.selectedRunID = -1;
        TestParent.TestRunInformationArrayList = null;
        TestParent.OverallResultsArrayList=null;
        TestParent.Top5SlowestPages=null;
        TestParent.Top5SlowestTestsArrayList=null;
        TestParent.PageResultsArrayList=null;
        TestParent.SystemUnderTestResourcesArrayList=null;
        TestParent.ErrorSummaryArrayList=null;
        TestParent.generatedFilePath="";
        TestParent.strtextBoxReportName="";
        TestParent.strtextAreaEnv="";
        TestParent.strtextBoxDeploymentDiag="";        
        TestParent.counterState = new Dictionary<String,Boolean>();
        TestParent.iSAllcounterChecked=false;

        for (int i = 0; i < checkedListReportOptions1.Items.Count; i++) checkedListReportOptions1.SetItemChecked(i, true);
        for (int i = 0; i < checkedListReportOptions2.Items.Count - 1; i++) checkedListReportOptions2.SetItemChecked(i, true);
        checkedListReportOptions2.SetItemChecked(checkedListReportOptions2.Items.Count - 1, false);
        }

        private void ChooseFileButtonClick(object sender, EventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.png";
            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                textBoxDeploymentDiag.Text = dlg.FileName;
            }
            this.listViewTestRuns.Focus();
        }

        private void buttonGenerateClick(object sender, EventArgs e)
        {
            storeUserPref();
            if (!copyDeploymentDiagram())
            {
                if (TestParent.strtextBoxDeploymentDiag.Contains("Choose the image file from your computer")) { }
                //MessageBox.Show("Invalid Deployment Diagram\nDo you want to skip the diagram ?");
                else if (MessageBox.Show("Invalid Deployment Diagram, Please check in the second tab.\nClick OK to continue, CANCEL to return", "Invalid Image !!!", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                { }
                else return;
            }
            reportWorker = new BackgroundWorker();
            reportWorker.WorkerReportsProgress = true;
            reportWorker.WorkerSupportsCancellation = true;
            reportWorker.DoWork += retrieveReportData;
            reportWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(reportWorker_RunWorkerCompleted);

            reportWorker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
            {
                int progress = args.ProgressPercentage;
                TestParent.ProgressPercentage = progress;
            };
            reportWorker.RunWorkerAsync();
            this.listViewTestRuns.Focus();
            showPopUp();
        }

        private bool copyDeploymentDiagram()
        {
            try
            {                
                File.Copy(TestParent.strtextBoxDeploymentDiag, "c:\\Templates\\Images\\deploymentDiagram.gif",true);
            }
            catch
            {
                return false;
            }
            return true;
        }

        private void storeUserPref()
        {
            String[] strArr = new String[3];

            strArr[0] = "strtextBoxReportName$" + textBoxReportName.Text;
            strArr[1] = "strtextAreaEnv$" + textAreaEnv.Text;
            strArr[2] = "strtextBoxDeploymentDiag$" + textBoxDeploymentDiag.Text;

            TestParent.strtextBoxReportName = textBoxReportName.Text;
            TestParent.strtextAreaEnv = textAreaEnv.Text;
            TestParent.strtextBoxDeploymentDiag = textBoxDeploymentDiag.Text;

            File.WriteAllLines("C:\\Templates\\userPref.txt", strArr);
        }

        public void showPopUp()
        {
            _ProgressWindow = new ProgressWindow();
            _ProgressWindow.Show(this);
        }


        private void retrieveReportData(object sender, EventArgs e)
        {
            TestParent.ProgressPercentage = 2;

            retrieveTestRunInformation();

            retrieveOverallResults();

            retrieveTop5SlowestPages();

            retrieveTop5SlowestTests();

            retrievePageResults();

            retrieveSystemUnderTestResources();

            retrieveErrorSummary();

            Thread.Sleep(200);

            TestParent.ProgressPercentage = 10;

            GraphPreparator _graphForm = new GraphPreparator();

            generate_from_HTMLReport();
            TestParent.ProgressPercentage = 100;
            Thread.Sleep(100);
        }

        private void generate_from_HTMLReport()
        {
            // create HTML report
            Dictionary<string, string> htmlDictionary = new Dictionary<string, string>();
            string allLines = global::LoadTestReport.Properties.Resources.HTMLProperties;
            string[] lines = allLines.Split('\n');

            for (int i = 0; i < lines.Length; i++)
            {
                string[] keyVal = lines[i].Split('$');
                htmlDictionary.Add(keyVal[0], keyVal[1]);
            }

            string indexHtml = "";
            indexHtml += htmlDictionary["DOCTYPE"];
            indexHtml += htmlDictionary["htmlStart"];
            indexHtml += htmlDictionary["head"];
            indexHtml += htmlDictionary["bodyStart"];
            indexHtml += htmlDictionary["firstTable"];
            indexHtml += htmlDictionary["brandLogo"];
            indexHtml += htmlDictionary["perfTestHeader"];
            indexHtml += htmlDictionary["projectNameHeader"];
            indexHtml += htmlDictionary["version"];

            string dateHeader = htmlDictionary["dateHeader"];
            dateHeader = dateHeader.Replace("10-Sep-2012", DateTime.Now.ToShortDateString());
            indexHtml += dateHeader;

            indexHtml += htmlDictionary["firstTableEnd"];
            indexHtml += htmlDictionary["br1"];

            String div1 = htmlDictionary["div1"];
            div1 = div1.Replace("10-Sep-2012", DateTime.Now.ToShortDateString());
            indexHtml += div1;

            indexHtml += htmlDictionary["br2"];
            indexHtml += htmlDictionary["toc"];
            indexHtml += htmlDictionary["br3"];
            indexHtml += htmlDictionary["executiveSummary"];
            indexHtml += htmlDictionary["purpose"];
            indexHtml += htmlDictionary["objective"];
            indexHtml += htmlDictionary["overView"];
            indexHtml += htmlDictionary["br4"];
            indexHtml += htmlDictionary["testEnvironment"];
            indexHtml += htmlDictionary["targetServers"];

            String[] envArr = TestParent.strtextAreaEnv.Split('\n');

            for (int i = 0, j = 1; i < envArr.Length; i++)
            {
                if (envArr[i] != "")
                {
                    indexHtml += "<li> <b>"+j+")</b> " + envArr[i] + "</li>";
                    j++;
                }
            }
            indexHtml += "</p><br><br><br>";
            indexHtml += htmlDictionary["deploymentDiagramText"];
            indexHtml += htmlDictionary["deploymentDiagramImg"];
            indexHtml += "<br><br><br><br>";
            indexHtml += htmlDictionary["loadgenerators"];
            indexHtml += htmlDictionary["testResults"];

            indexHtml += htmlDictionary["testResultsStart"];
            
            //append test run summary start

            indexHtml += htmlDictionary["resultSummaryTableHeader"];
            Dictionary<String, String> Dict = (Dictionary<String, String>)TestParent.TestRunInformationArrayList[0];
            String table = "";
            foreach (KeyValuePair<String, String> entry in Dict)
            {
                if (entry.Key == "runID") { }
                else if (entry.Key == "testName") table += "<tr><td style='height:10px;'> Test Name</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                else if (entry.Key == "description") table += "<tr><td style='height:10px;'> Description</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                else if (entry.Key == "startTime") table += "<tr><td style='height:10px;'> Start Time</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                else if (entry.Key == "endTime") table += "<tr><td style='height:10px;'> End Time</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                else if (entry.Key == "runDuration")
                {
                    int val = 0;
                    try
                    {
                        val = int.Parse(entry.Value);
                        val = val / 60;
                    }
                    catch { val = 0; }

                    table += "<tr><td style='height:10px;'> Run Duration</td><td style='height:10px;' align='center'>" + val + " Minutes. </td></tr>"; 
                }
                else if (entry.Key == "WarmupTime") 
                {
                    int val = 0;
                    try
                    {
                        val = int.Parse(entry.Value);
                        val = val / 60;
                    }
                    catch { val = 0; }
                    table += "<tr><td style='height:10px;'> Warmup Time</td><td style='height:10px;' align='center'>" + val + " Minutes. </td></tr>"; 
                }
                else if (entry.Key == "RunSettingUsed") table += "<tr><td style='height:10px;'> Run Setting Name</td><td style='height:10px;' align='center'>" + entry.Value + " </td></tr>";
                else if (entry.Key == "outcome") table += "<tr><td style='height:10px;'> Outcome of the Test</td><td style='height:10px;' align='center'>" + entry.Value + " </td></tr>";
                else if (entry.Key == "CooldownTime")
                {
                    int val = 0;
                    try
                    {
                        val = int.Parse(entry.Value);
                        val = val / 60;
                    }
                    catch { val = 0; }
                    table += "<tr><td style='height:10px;'> Cooldown Time</td><td style='height:10px;' align='center'>" + val + " Minutes. </td></tr>";
                }
            }
            table += "</table></p></p></div>";
            indexHtml += table;
            table = "";
            //append test run summary end
            indexHtml += "<br><br><br><br><br><br>";

            try
            {
                //append overal test results start
                indexHtml += "<p><font size='large'>3.2 Overall Test Results</font>";
                indexHtml += "<p><table width='100%' border='1'><tr><td style='height:10px;' width='50%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Test Result Information</font></td><td style='height:10px;' width='50%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Value</font></td></tr>";

                //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                for (int i = 0; i < TestParent.OverallResultsArrayList.Count; i++)
                {
                    Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.OverallResultsArrayList[i];
                    var entry = dict.ElementAt(0);
                    table += "<tr><td style='height:10px;'> " + entry.Key + "</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                }
                indexHtml += table + "</table></p></p>";

                //append overal test results end
            }
            catch { }


            
            indexHtml += "<br><br><br><br><br><br>";

            //Append top 5 slow pages start
            try
            {
                table = "";

                indexHtml += "<p><font size='large'>3.3 Top 5 Slowest Pages</font>";
                indexHtml += "<p><table width='100%' border='1'><tr><td style='height:10px;' width='75%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Page Name</font></td><td style='height:10px;' width='25%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Response Time</font></td></tr>";

                //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                for (int i = 0; i < TestParent.Top5SlowestPages.Count; i++)
                {
                    Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.Top5SlowestPages[i];
                    var entry = dict.ElementAt(0);
                    table += "<tr><td style='height:10px;'> " + entry.Key + "</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                }
                indexHtml += table + "</table></p></p>";
            }
            catch { }
            //Append top 5 slow pages end


            indexHtml += "<br><br><br><br><br><br>";

            //Append Top 5 Slowest Tests start
            try
            {
                table = "";

                indexHtml += "<p><font size='large'>3.4 Top 5 Slowest Tests</font>";
                indexHtml += "<p><table width='100%' border='1'><tr><td style='height:10px;' width='75%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Test Name</font></td><td style='height:10px;' width='25%' bgcolor='#9999FF' align='center'><font size='medium' color='white'>Response Time</font></td></tr>";

                //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                for (int i = 0; i < TestParent.Top5SlowestTestsArrayList.Count; i++)
                {
                    Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.Top5SlowestTestsArrayList[i];
                    var entry = dict.ElementAt(0);
                    table += "<tr><td style='height:10px;'> " + entry.Key + "</td><td style='height:10px;' align='center'>" + entry.Value + "</td></tr>";
                }
                indexHtml += table + "</table></p></p>";
            }
            catch { }
            //Append Top 5 Slowest Tests end

             indexHtml += "<br>";

             //Append Page Results start
             try
             {
                 table = "";

                 indexHtml += "<p><font size='large'>3.5 Page Results</font>";
                 indexHtml += "<p><table width='100%' border='1'><tr>";

                 var reskeys = ((Dictionary<String, String>)TestParent.PageResultsArrayList[0]).Keys;


                 for (int i = 1; i < reskeys.Count; i++)
                 {
                     indexHtml += "<td style='height:10px;' bgcolor='#9999FF' align='center'><font size='small' color='white'>" + reskeys.ElementAt(i) + "</font></td>";
                 }

                 indexHtml += "</tr>";

                 //Dictionary<String, String> Dict1 = (Dictionary<String, String>);
                 for (int i = 0; i < TestParent.PageResultsArrayList.Count; i++)
                 {
                     Dictionary<String, String> dict = (Dictionary<String, String>)TestParent.PageResultsArrayList[i];
                     var values = dict.Values;
                     indexHtml += "<tr>";
                     for (int ii = 1; ii < values.Count; ii++)
                     {
                         string DVal = "";

                         try
                         {
                             DVal = Math.Round(decimal.Parse(values.ElementAt(ii)), 2).ToString();
                         }
                         catch
                         {
                             DVal = values.ElementAt(ii);
                         }

                         indexHtml += "<td style='height:10px;' align='left'><font size='x-small' color='black'>" + DVal + "</font></td>";
                     }
                     indexHtml += "</tr>";
                 }
                 indexHtml += table + "</table></p></p>";
             }
             catch { }
            //Append Page Results end

            //Append Graphs start
             if (!Directory.Exists("C:\\Templates\\Images\\Graphs"))
             {
                 Directory.CreateDirectory("C:\\Templates\\Images\\Graphs");
             }

             string[] graphsArr = Directory.GetFiles("C:\\Templates\\Images\\Graphs", "*.jpg");

             for (int g = 0; g < graphsArr.Length; g++)
             {
                 graphsArr[g] = graphsArr[g].Replace("\\","/");
             }

             ArrayList graphs = new ArrayList(graphsArr);
             String cpuGraphPath = "";

             String ramGraphPath = "";

             for (int g = 0; g < graphs.Count; g++)
             {                 
                 if (graphs[g].ToString().EndsWith("-Processor-Time.jpg"))
                 {
                     cpuGraphPath = (graphs[g].ToString()).Replace("C:/Templates","");
                     graphs.Remove(graphs[g]);
                 }                 
             }

             for (int g = 0; g < graphs.Count; g++)
             {
                 if (graphs[g].ToString().EndsWith("Available-MBytes.jpg"))
                 {
                     ramGraphPath = (graphs[g].ToString()).Replace("C:/Templates","");
                     graphs.Remove(graphs[g]);
                 }
             }

             if (cpuGraphPath != "" || ramGraphPath != "")
             {
                 indexHtml += "<br><br><p><font size=\"large\">4. Primary Usage Graphs</font><table>";
             }
            
             if (cpuGraphPath != "")
             {
                 indexHtml += "<tr><td><font size='medium'>4.1 CPU Usage</font><img src=\"." + cpuGraphPath + "\" height=\"200\" width=\"600\" alt='Image'></img></td></tr>";
             }
             if (ramGraphPath != "")
             {
                 indexHtml += "<tr><td><font size='medium'>4.2 RAM Usage</font><img src=\"." + ramGraphPath + "\" height=\"200\" width=\"600\" alt='Image'></img></td></tr>";
             }

             if (cpuGraphPath != "" || ramGraphPath != "")
             {
                 indexHtml += "</table></p>";
             }

             if (graphs.Count > 0) indexHtml += "<br><br><br><br><p><font size=\"large\">5. Other Counters Graphs</font><table>";

            for(int gr = 0 ; gr < graphs.Count ; gr++)
            {
                String graphFileName = (graphs[gr].ToString()).Replace("C:/Templates","");                
                String graphName = Regex.Replace(graphFileName, "[^0-9a-zA-Z]+", " ");

                graphName = graphName.Replace("Images Graphs", "");
                graphName = graphName.Replace("jpg", "");

                indexHtml += "<tr><td><font size='medium'>5." + (gr + 1) + " " + graphName + "</font><img src=\"." + graphFileName + "\" height=\"200\" width=\"600\" alt='Image'></img></td></tr>";
            }
             //Append Graphs end
            if (graphs.Count > 0) indexHtml += "</table></p>";
             indexHtml += "</body></html>";

            String rootPath = "C:\\Templates\\";

            if (!Directory.Exists(rootPath))
            { 
                Directory.CreateDirectory(rootPath);
                Directory.CreateDirectory(rootPath + "//Images");
            }

            File.WriteAllText(rootPath+"index.html", indexHtml);

            // HTML to DOCX conversion            
            MyWebServer MWS = null;
            try
            {
                MWS = new MyWebServer();

                Thread.Sleep(300);

                using (WebClient client = new WebClient())
                {
                    client.Headers["User-Agent"] =
                    "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                    "(compatible; MSIE 6.0; Windows NT 5.1; " +
                    ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                    // Download data.
                    string html = client.DownloadString("http://localhost:5050/index.html");

                    TestParent.ProgressPercentage = 95;

                    using (MemoryStream generatedDocument = new MemoryStream())
                    {
                        using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                        {
                            MainDocumentPart mainPart = package.MainDocumentPart;
                            if (mainPart == null)
                            {
                                mainPart = package.AddMainDocumentPart();
                                new Document(new Body()).Save(mainPart);
                            }
                            HtmlConverter converter = new HtmlConverter(mainPart);
                            converter.BaseImageUrl = new Uri("http://localhost:5050");
                            Body body = mainPart.Document.Body;

                            var paragraphs = converter.Parse(html);

                            for (int i = 0; i < paragraphs.Count; i++)
                            {
                                body.Append(paragraphs[i]);
                            }
                            mainPart.Document.Save();
                        }

                        TestParent.bytesGeneratedDocument = generatedDocument.ToArray();

                        TestParent.ProgressPercentage = 100;
                    }
                    MWS.StopListen();
                }
            }
            catch 
            {
                string[] filesArr = Directory.GetFiles("C:\\Templates\\Images\\Graphs", "*.jpg");
                for (int i = 0; i < filesArr.Length; i++)
                {
                    File.Delete(filesArr[i]);
                }
                if (MWS !=null) MWS.StopListen();
                TestParent.ProgressPercentage = 100;
            }
        }

        private void retrieveErrorSummary()
        {
            TestParent.ErrorSummaryArrayList = DAO.DataReader.getErrorSummary(TestParent.selectedRunID);
        }

        private void retrieveSystemUnderTestResources()
        {
            TestParent.SystemUnderTestResourcesArrayList = DAO.DataReader.getSystemUnderTestResources(TestParent.selectedRunID);
        }

        private void retrievePageResults()
        {
            TestParent.PageResultsArrayList = DAO.DataReader.getPageResults(TestParent.selectedRunID);
        }

        private void retrieveTop5SlowestTests()
        {
            TestParent.Top5SlowestTestsArrayList = DAO.DataReader.getTop5SlowestTests(TestParent.selectedRunID);
        }

        private void retrieveTop5SlowestPages()
        {
            TestParent.Top5SlowestPages = DAO.DataReader.getTop5SlowestPages(TestParent.selectedRunID);
        }

        private void retrieveOverallResults()
        {
            TestParent.OverallResultsArrayList = DAO.DataReader.getOverallResults(TestParent.selectedRunID);
        }

        private void retrieveTestRunInformation()
        {
            TestParent.TestRunInformationArrayList = DAO.DataReader.getTestRunInformation(TestParent.selectedRunID);
        }
        void reportWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _ProgressWindow.Close();

            string filename = TestParent.strtextBoxReportName + ".docx";

            if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + filename))
            {
                if (MessageBox.Show("A File by name \"" + filename + "\" already exists on User Desktop.\n Do you want to Overwrite?", "Confirm Overwrite !!!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    try
                    {
                        File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + filename, TestParent.bytesGeneratedDocument);
                        TestParent.generatedFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + filename;
                    }
                    catch (Exception ex)
                    {
                        if (MessageBox.Show(ex.Message+"\n Save as different name ?", "Overwrite Error !!!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
                            saveFileDialog1.Title = "Save As";
                            saveFileDialog1.InitialDirectory = Convert.ToString(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
                            saveFileDialog1.Filter = "MS Word File (*.docx)|*.docx|All Files (*.*)|*.*";
                            saveFileDialog1.FilterIndex = 1;
                            saveFileDialog1.FileName = filename;
                            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                            {
                                try
                                {
                                    File.WriteAllBytes(saveFileDialog1.FileName, TestParent.bytesGeneratedDocument);
                                    filename = saveFileDialog1.FileName;
                                    TestParent.generatedFilePath = filename;
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show("Writing failed. Please close the open report and try again !!!");
                                }
                            }
                        }
                    }
                }
                else
                {
                    System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
                    saveFileDialog1.Title = "Save As";
                    saveFileDialog1.InitialDirectory = Convert.ToString(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
                    saveFileDialog1.Filter = "MS Word File (*.docx)|*.docx|All Files (*.*)|*.*";
                    saveFileDialog1.FilterIndex = 1;
                    saveFileDialog1.FileName = filename;
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        File.WriteAllBytes(saveFileDialog1.FileName, TestParent.bytesGeneratedDocument);
                        filename = saveFileDialog1.FileName;
                        TestParent.generatedFilePath = filename;
                    }
                }
            }
            else
            {
                File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + filename, TestParent.bytesGeneratedDocument);
                TestParent.generatedFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + filename;
            }                        

            if (MessageBox.Show("File successfully generatetd and copied to Desktop, Open ?", "Confirm Open !!!", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Process.Start(TestParent.generatedFilePath);   
            }
            string[] graphsArr = Directory.GetFiles("C:\\Templates\\Images\\Graphs", "*.jpg");
            for (int i = 0; i < graphsArr.Length; i++)
            {
                File.Delete(graphsArr[i]);
            }
            this.listViewTestRuns.Focus();
        }

        private void saveButtonClicked(object sender, EventArgs e)
        {
            storeUserPref();
        }
    }
}
